﻿using System;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using WeBlog.Interfaces;
using WeBlog.Models;
using WeBlog.Repositories;

namespace WeBlog.Services.BlogML
{
    /// <summary>
    /// Blog Importer
    /// </summary>
    public class BlogImporter
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly PostRepository _postRepository;


        public BlogImporter( IUnitOfWork unitOfWork )
        {
            _unitOfWork = unitOfWork;
            _postRepository = new PostRepository(unitOfWork);
        }

        /// <summary>
        /// Add new blog post to system
        /// </summary>
        /// <returns>
        /// string containing unique post identifier
        /// </returns>
        public string AddPost(BlogMlExtendedPost extPost)
        {
            //if (!Security.IsAdministrator)
            //{
            //    throw new InvalidOperationException("BlogImporter.AddPost: Wrong credentials");
            //}

            var p = new Post
                        {
                            Title = extPost.BlogPost.Title,
                            DateCreated = extPost.BlogPost.DateCreated,
                            LastModified = extPost.BlogPost.DateModified,
                            Content = extPost.BlogPost.Content.UncodedText,
                            Description = extPost.BlogPost.Excerpt.UncodedText,
                            Published = extPost.BlogPost.Approved,                    
                            Categories=extPost.Categories,
                            PostComments = extPost.Comments                            
                        };

            if (!string.IsNullOrEmpty(extPost.PostUrl))
            {
                // looking for a Slug with patterns such as:
                //    /some-slug.aspx
                //    /some-slug.html
                //    /some-slug
                //
                Match slugMatch = Regex.Match(extPost.PostUrl, @"/([^/\.]+)(?:$|\.[\w]{1,10}$)", RegexOptions.IgnoreCase);
                if (slugMatch.Success)
                    p.Slug = slugMatch.Groups[1].Value.Trim();
            }

            if(extPost.BlogPost.Authors != null && extPost.BlogPost.Authors.Count > 0)
                p.AuthorId = Convert.ToInt32(extPost.BlogPost.Authors[0].Ref);
            //error is hiding here! MemoryOutOfException throwing
            if (extPost.Categories != null && extPost.Categories.Count > 0)
            {
                foreach (var i in extPost.Categories.ToList())
                    p.Categories.Add(i);
            }
            

            if(extPost.Tags != null && extPost.Tags.Count > 0)
                extPost.Tags.ForEach(x => p.Tags.Add(new Tag() { Name = x }));                

            // skip if post with same slug already exists
            var exists = _postRepository.FindAll().Any(x => x.Slug == p.Slug);            
            if( exists )            
                return string.Empty;            
            if(extPost.Comments != null && extPost.Comments.Count > 0)
            {
                foreach (var comment in extPost.Comments.ToList())
                {
                    p.PostComments.Add(comment);
                }
            }

            _unitOfWork.Commit();            
            return p.PostId.ToString();
        }
    }
}